<script setup lang="ts">
import type { Recordable } from '@vben/types';

import type { UserProfile } from '#/api/user/sysuser/profile';

import { onMounted } from 'vue';

import { ElMessage } from 'element-plus';
import { pick } from 'lodash-es';

import { useVbenForm } from '#/adapter/form';
import { USER_DICT } from '#/api';
import { editProfile } from '#/api/user/sysuser/profile';
import { $t } from '#/locales';

const props = defineProps<{ profile: UserProfile }>();

const emit = defineEmits<{ reload: [] }>();

const [BasicForm, formApi] = useVbenForm({
  actionWrapperClass: 'text-left ml-[68px] mb-[16px]',
  commonConfig: {
    labelWidth: 60,
  },
  handleSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      fieldName: 'nickname',
      label: '昵称',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.man'), value: USER_DICT.GENDER_MAN },
          { label: $t('common.woman'), value: USER_DICT.GENDER_WOMAN },
          { label: $t('common.unknown'), value: USER_DICT.GENDER_UNKNOWN },
        ],
        optionType: 'button',
      },
      defaultValue: '0',
      fieldName: 'gender',
      label: '性别',
    },
  ],
  submitButtonOptions: {
    text: true,
  },
});

function buttonLoading(loading: boolean) {
  formApi.setState((prev: any) => ({
    ...prev,
    submitButtonOptions: { ...prev.submitButtonOptions, loading },
  }));
}

async function handleSubmit(values: Recordable<any>) {
  try {
    buttonLoading(true);
    editProfile(values).then(() => {
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
      // 左边reload
      emit('reload');
    });
  } catch (error) {
    console.error(error);
  } finally {
    buttonLoading(false);
  }
}

onMounted(() => {
  const data = pick(props.profile.user, ['nickname', 'gender']);
  for (const key in data) {
    formApi.setFieldValue(key, data[key as keyof typeof data]);
  }
});
</script>

<template>
  <div class="mt-[16px] md:w-full lg:w-1/2 2xl:w-2/5">
    <BasicForm />
  </div>
</template>
